#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MSTK.h"


int main(int argc, char *argv[]) {
  int k, len, suff, ok;
  char mname[256], filename[256];
  Mesh_ptr mesh;


  if (argc == 1) {
    fprintf(stdout, "mstk2gmv converts a mstk mesh into gmv format\n");
    fprintf(stdout, "Usage: mstk2gmv filename\n");
    return -1;
  }

  fprintf(stderr,"\n");


  /* Initialize MSTK - Always do this even if it does not seem to
     matter in this version of MSTK */

  MSTK_Init();

  /* Load the mesh */

  strcpy(mname,argv[1]);
  len = strlen(mname);
  suff = 0;
  if (len > 5) {
    k = len-5;
    while (!suff && k > 1) {
      if (strncmp(&(mname[k]),".mstk",5) == 0) {
        suff = 1;
      }
      else
        k--;
    }
  }
  if (suff)
    mname[len-5] = '\0';

  strcpy(filename,mname);
  strcat(filename,".mstk");

  mesh = MESH_New(UNKNOWN_REP);
  ok = MESH_InitFromFile(mesh,filename);
  if (!ok) {
    fprintf(stderr,"Cannot open input file %s\n\n\n",filename);
    exit(-1);
  }

  /* Write out a copy of the mesh */

  strcpy(filename,mname);
  strcat(filename,".gmv");
  MESH_ExportToGMV(mesh,filename,0,NULL,NULL);
  fprintf(stdout,"gmv file %s has been generated\n",filename);
  
  /* Deleting of mesh is not necessary if this the end of the program */

  MESH_Delete(mesh);

  return 1;
}
